package com.hotel.meals.service.impl;

import cn.hutool.core.convert.NumberWithFormat;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotel.common.config.SystemConfig;
import com.hotel.common.param.Cart;
import com.hotel.common.param.GetFood;
import com.hotel.common.util.JwtUtil;
import com.hotel.meals.mapper.CartItemMapper;
import com.hotel.meals.service.CartItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hotel.user.entity.CartItem;
import com.hotel.user.entity.ResponseDTO;
import com.hotel.user.entity.UserWallet;
import com.hotel.meals.mapper.UserWalletMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author KK
 * @since 2024-06-19
 */
@Service
public class CartItemServiceImpl extends ServiceImpl<CartItemMapper, CartItem> implements CartItemService {

    @Autowired
    private CartItemMapper cartItemMapper;

    @Autowired
    private UserWalletMapper userWalletMapper;

    @Override
    public ResponseDTO<List<CartItem>> checkout(Cart cart, HttpServletRequest request) {
        String token = request.getHeader(SystemConfig.HEADER_TOKEN);
        int id = ((NumberWithFormat) JwtUtil.parseToken(token, "id")).intValue();
        QueryWrapper<UserWallet> userWalletQueryWrapper = new QueryWrapper<>();
        userWalletQueryWrapper.eq("user_id", id);
        UserWallet userWallet = userWalletMapper.selectOne(userWalletQueryWrapper);
        CartItem cartItems = new CartItem();
        cartItems.setUserId(id);
        List<CartItem> cartItemList = new ArrayList<>();
        String foodList = cart.getFoodCartList();
        List<GetFood> foods = JSONArray.parseArray(foodList, GetFood.class);
        double allSum = 0.0;
        for (GetFood food : foods) {
            double sum = food.getPrice() * food.getQuantity();
            allSum+=sum;
        }
        if (userWallet.getMoney() < allSum){
            return new  ResponseDTO<>(500,"钱包余额不足，购买失败！",null);
        }else {
            for (GetFood food : foods) {
                cartItems.setFoodId(food.getId());
                cartItems.setQuantity(food.getQuantity());
                cartItemList.add(cartItems);
            }
            //扣除钱
            userWallet.setMoney((int) (userWallet.getMoney()-allSum));
            //将修改后的余额插入到数据库中
            userWalletMapper.updateById(userWallet);
            cartItemMapper.insertBatch(cartItemList);
            return new  ResponseDTO<>(200,"购买成功",cartItemList);
        }

    }
}
